package com.maimao.goods.utils;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.maimao.core.constant.ListData;
import org.ansj.splitWord.analysis.NlpAnalysis;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.*;

/**
 * @author MaoLin Wang
 * @date 2021/1/30 2:20 下午
 */
public class HotWordUtil {
    private static List<String> HOW_WORDS = null;

    public static List<Map<String, Object>> wordFrequency(String article, int top)  {
        Map<String, Integer> map = new HashMap<String, Integer>();
        String result = NlpAnalysis.parse(article).toStringWithOutNature();
        System.out.println(result);
        String[] words = result.split(",");


        for (String word : words) {
            String str = word.trim();
            // 过滤空白字符
            if (str.equals(""))
                continue;
                // 过滤一些高频率的符号
            else if (str.matches("[）|（|.|，|。|+|-|“|”|：|？|\\s]"))
                continue;
                // 此处过滤长度为1的str
            else if (str.length() < 2)
                continue;

            if (!map.containsKey(word)) {
                map.put(word, 1);
            } else {
                int n = map.get(word);
                map.put(word, ++n);
            }
        }
        if (ObjectUtils.isEmpty(HOW_WORDS)) {
            HOW_WORDS = stopWords();
        }
        Set<String> strings = map.keySet();
        strings.removeAll(HOW_WORDS);
        List<Map<String, Object>> list = new ArrayList<>();

        if (strings.size() <= 0) {
            return list;
        }
        Map<String, Integer> lastMap = Maps.newHashMapWithExpectedSize(map.size());
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            if (strings.contains(entry.getKey())) {
                lastMap.put(entry.getKey(), entry.getValue());
            }
        }

        Map.Entry<String, Integer> entry;

        while ((entry = getMax(lastMap)) != null) {
            Map<String, Object> res = Maps.newHashMapWithExpectedSize(2);
            res.put("word", entry.getKey());
            res.put("count", entry.getValue());
            list.add(res);
        }
        if (top > 0 && list.size() >= top) {
            return list.subList(0, top);
        }
        return list;

    }

    public static List<String> stopWords()  {
        // 中文 停用词 .txt 文件路径
        String filePath = "/Users/wangmaolin/IdeaProjects/maimao/maimao_server/maimao_parent/maimao_goods/src/main/resources/stopWords";
        File file = new File(filePath);

        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new FileReader(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();

            return ListData.EMPTY_LIST;
        }
        List<String> stopWords = new ArrayList<>();
        String temp = null;
        while (true) {
            try {
                if (!!StringUtils.isEmpty((temp = bufferedReader.readLine()))) break;
            } catch (IOException e) {
                e.printStackTrace();
            }
            stopWords.add(temp.trim());
        }
        return stopWords;

    }


    /**
     * 找出map中value最大的entry, 返回此entry, 并在map删除此entry
     *
     * @param map
     * @return
     */
    public static Map.Entry<String, Integer> getMax(Map<String, Integer> map) {
        if (map.size() == 0) {
            return null;
        }
        Map.Entry<String, Integer> maxEntry = null;
        boolean flag = false;
        Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Integer> entry = iterator.next();

            if (!flag) {
                maxEntry = entry;
                flag = true;
            }
            if (entry.getValue() > maxEntry.getValue()) {
                maxEntry = entry;
            }
        }
        map.remove(maxEntry.getKey());
        return maxEntry;
    }

    /**
     * 从文件中读取待分割的文章素材.
     *
     * @return
     * @throws IOException
     */
    public static String getString() throws IOException {
        FileInputStream inputStream = new FileInputStream(new File("e://a.txt"));
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder strBuilder = new StringBuilder();

        String line;
        while ((line = reader.readLine()) != null) {
            strBuilder.append(line);
        }
        reader.close();
        inputStream.close();
        return strBuilder.toString();
    }

}
